package cn.virens.server.netty_udp;

import java.io.Serializable;
import java.net.InetSocketAddress;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

import io.netty.buffer.Unpooled;
import io.netty.channel.socket.DatagramPacket;

public class UDPServerChannel implements Serializable {
	private static final long serialVersionUID = -947516044734319749L;

	private final Map<String, Object> attrs = new ConcurrentHashMap<>();

	private final AtomicInteger heatTimes = new AtomicInteger(0);
	private final AtomicInteger heatIdle = new AtomicInteger(0);

	private final Object lock = new Object();

	private InetSocketAddress addr;

	private final String mac;

	protected UDPServerChannel(String mac) {
		this.mac = mac;
	}

	protected final UDPServerChannel warp(InetSocketAddress addr) {
		synchronized (lock) {
			this.addr = addr;
		}

		return this;
	}

	public String getMac() {
		return mac;
	}

	public InetSocketAddress getAddr() {
		synchronized (lock) {
			return addr;
		}
	}

	@SuppressWarnings("unchecked")
	public <T> T getAttr(String key) {
		return (T) attrs.get(key);
	}

	@SuppressWarnings("unchecked")
	public <T> T setAttr(String key, T value) {
		return (T) attrs.put(key, value);
	}

	public AtomicInteger heatIdle() {
		return heatIdle;
	}

	public AtomicInteger heatTimes() {
		return heatTimes;
	}

	/**
	 * 对要发送的byte数组封包
	 * 
	 * @param  bs byte数组
	 * @return    封包对象
	 */
	public final DatagramPacket wrap(byte[] bs) {
		return new DatagramPacket(Unpooled.copiedBuffer(bs), addr);
	}

	@Override
	public int hashCode() {
		return Objects.hashCode(addr);
	}

	@Override
	public boolean equals(Object obj) {
		return Objects.hashCode(obj) == hashCode();
	}

	@Override
	public String toString() {
		return addr + "[" + mac + "]";
	}

}
